<template>
  <el-scrollbar>
    <div :class="{ hidden: hidden }" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="limit"
        :background="background"
        :layout="layout"
        :page-sizes="pageSizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { computed } from "vue";
defineOptions({
  name: "OffsetPagination",
  inheritAttrs: false,
});

const props = defineProps({
  total: {
    type: Number as PropType<number>,
    default: 0,
  },
  pageSizes: {
    type: Array as PropType<number[]>,
    default() {
      return [10, 20, 30, 50];
    },
  },
  layout: {
    type: String,
    default: "total, sizes, prev, pager, next, jumper",
  },
  background: {
    type: Boolean,
    default: true,
  },
  autoScroll: {
    type: Boolean,
    default: true,
  },
  hidden: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["pagination"]);

const offset = defineModel("offset", {
  type: Number,
  required: true,
  default: 0,
});

const limit = defineModel("limit", {
  type: Number,
  required: true,
  default: 10,
});

const currentPage = computed({
  get: () => Math.floor(offset.value / limit.value) + 1,
  set: (val: number) => {
    offset.value = (val - 1) * limit.value;
  },
});

watch(
  () => props.total,
  (newVal: number) => {
    const lastPage = Math.ceil(newVal / limit.value);
    if (newVal > 0 && offset.value > lastPage * limit.value) {
      offset.value = lastPage * limit.value;
      emit("pagination", { offset: offset.value, limit: limit.value });
    }
    // if (newVal > 0 && currentPage.value > lastPage) {
    //   currentPage.value = lastPage;
    //   emit("pagination", { page: currentPage.value, limit: pageSize.value });
    // }
  }
);

function handleSizeChange(val: number) {
  // currentPage.value = 1;
  // emit("pagination", { page: currentPage.value, limit: val });
  offset.value = 0;
  limit.value = val;
  emit("pagination", { offset: offset.value, limit: limit.value });
}

function handleCurrentChange(val: number) {
  // emit("pagination", { page: val, limit: pageSize.value });
  offset.value = (val - 1) * limit.value;
  emit("pagination", { offset: offset.value, limit: limit.value });
}
</script>

<style lang="scss" scoped>
.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  padding: 12px;

  &.hidden {
    display: none;
  }
}
</style>
